import util from '../../utils/util';
import eycService from "../../js/eycService";
import {routerFilter} from '../../utils/routerFilter';
import consts from "../../js/const";
import calcDate from "../../js/calcDate";
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
routerFilter({

    /**
     * 页面的初始数据
     */
    data: {
        currentDate: new Date().getTime(),
        minDate: new Date().getTime(),
        eycOrder: {
            contactNum: util.getStorageSync(consts.cache_key.PHONE_NUMBER),
            isDoorPickUp: 0,
            isDoorPickUpNme: '否'
        },
        couponCount: 0,
        doorPickUpItems: [
            {
                name: '是',
                code: 1
            },
            {
                name: '否',
                code: 0
            }
        ],
        pickUpTimeItems: [
            {
                name: '08:00-09:00',
                code: '08:00-09:00'
            },
            {
                name: '09:00-10:00',
                code: '09:00-10:00'
            },
            {
                name: '10:00-11:00',
                code: '10:00-11:00'
            },
            {
                name: '11:00-12:00',
                code: '11:00-12:00'
            },
            {
                name: '12:00-13:00',
                code: '12:00-13:00'
            },
            {
                name: '13:00-14:00',
                code: '13:00-14:00'
            }
        ],
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this;
        let data = that.data;
        if (options.isEdit) {
            data.isEdit=options.isEdit;
            const eventChannel = that.getOpenerEventChannel();
            eventChannel.on('acceptDataFromOrderListPage', function (eycOrder) {
                data.currentDate=new Date(eycOrder.appointmentDt).getTime();
                eycOrder.isDoorPickUpNme=eycOrder.isDoorPickUp?'是':'否';
                data.eycOrder=eycOrder;
                that.setData(data);
                util.promise('/searchEycVehicleFileByPlateNum',eycOrder.plateNum).then((res)=>{
                    if(res.data){
                        that.refreshVehicleFile(res.data);
                    }

                })
            });
        } else {
            util.promise('/baseConfig/searchPageConfigByTypeCde', {
                isRequestParam: true,
                pageCde: 'checkVehicle',
                typeCde: 'CAROUSEL',
                status: 'FILE'
            }).then(function (res) {
                data.carousels = res.data;
                that.setData(data);
            });

            that.isLogin(null, function () {
                let initEycVehicleFile = function () {
                    eycService.searchEycVehicleFileByUserId().then(function (res) {
                        if (!util.isEmptyObject(res.data)) {
                            let vehicleFile = null;
                            res.data.forEach(function (vehicle) {
                                if (vehicle.isDefault) {
                                    vehicleFile = vehicle;
                                }
                            });
                            that.refreshVehicleFile(vehicleFile || res.data[0]);
                        }
                    });
                };
                util.promise('/searchEycUser').then(res => {
                    if (res.data) {
                        data.eycOrder = data.eycOrder || {};
                        data.eycOrder.contact = res.data.nickName;
                        that.setData(data);
                    }
                });
                util.promise('/searchCountCouponByUserId').then(res => {
                    if (res.data > 0) {
                        that.setData({couponCount: res.data});
                        util.promise('/searchOneCouponByUserId').then(res => {
                            if (res.data) {
                                data.coupon = res.data;
                                data.eycOrder = data.eycOrder || {};
                                data.eycOrder.couponId = data.coupon.eycCouponId;
                                data.eycOrder.couponPrice = data.coupon.amount;
                                that.setData(data);
                            }
                            initEycVehicleFile();
                        });
                    } else {
                        initEycVehicleFile();
                    }
                });
            });
        }
        let day = new Date().getDate();
        let maxDate = new Date(util.addDays(new Date(util.addMonths(new Date(), 3).setDate(1)), -1));
        if (day <= 15) {
            maxDate = new Date(util.addDays(new Date(util.addMonths(new Date(), 2).setDate(1)), -1));
        }
        that.setData({maxDate: maxDate.getTime()});
        //that.initAppointmentDate();
    },
    initAppointmentDate(inspStationId) {
        let that = this;
        let maxDate = new Date(that.data.maxDate);
        util.promise('/baseConfig/searchInspStationWorkdays', {
            startDate: util.formatTime(new Date()),
            endDate: util.formatTime(maxDate)
        }).then(function (res) {
            let rows = res.data;
            if (!util.isEmptyObject(rows)) {
                let appointmentDtFormatter = function (day) {
                    let date = util.formatTime(day.date);
                    let days = day.date.getDay();
                    if (days === 0) {
                        day.topInfo = '休';
                        day.type = 'disabled';
                    }
                    rows.forEach(function (row) {
                        if (!row.inspStationId) {
                            if (row.dayOffToWd === date) {
                                day.topInfo = '班';
                                day.type = '';
                                day.bottomInfo = row.remark ? row.remark : '';
                            } else if (row.wdToDayOff === date) {
                                day.topInfo = '休';
                                day.type = 'disabled';
                                day.bottomInfo = row.remark ? row.remark : '';
                            }
                        }

                    })
                    if (inspStationId) {
                        rows.forEach(function (row) {
                            if (row.inspStationId === inspStationId) {
                                if (row.dayOffToWd === date) {
                                    day.topInfo = '班';
                                    day.type = '';
                                    day.bottomInfo = row.remark ? row.remark : '';
                                } else if (row.wdToDayOff === date) {
                                    day.topInfo = '休';
                                    day.type = 'disabled';
                                    day.bottomInfo = row.remark ? row.remark : '';
                                }
                            }
                        })
                    }

                    return day;
                }
                that.setData({appointmentDtFormatter: appointmentDtFormatter});
            }
        });
        that.checkAppointedDayPickupCarNum();
    },
    getUserProfile(e) {
        let that = this;
        let data = that.data;
        wx.getUserProfile({
            desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                let userInfo = res.userInfo;
                data.eycOrder.contact = userInfo.nickName;
                that.setData(data);
            }
        })
    },
    refreshVehicleFile: function (vehicleFile) {
        let that = this;
        let data = that.data;
        data.selectVehicle = vehicleFile;
        data.eycOrder.plateNum = data.selectVehicle.plateNum;
        that.setData(data);
        if (vehicleFile.registerDt) {
            util.promise('/baseConfig/searchMatchInspRule', vehicleFile).then(function (res) {
                if (res.data) {
                    let endDate = calcDate.caleInspEndDate(new Date(vehicleFile.registerDt), res.data);
                    data.eycOrder.endDate = util.formatTime(endDate);
                    data.eycOrder.startDate = util.formatTime(calcDate.caleInspStartDate(endDate, -1 * res.data.inspAdvanceMonths));
                    that.setData(data);
                }

            });
        }
        util.promise('/baseConfig/searchMatchInspPriceRule', vehicleFile).then(function (res) {
            let inspPriceRule = res.data;
            if (inspPriceRule) {
                let eycOrder = data.eycOrder || {};
                eycOrder.costPrice = (inspPriceRule.safetyInspRate || 0) + (inspPriceRule.compInspRate || 0) + (inspPriceRule.epInspRate || 0);
                eycOrder.preferentialPrice = inspPriceRule.preferentialPrice ? inspPriceRule.preferentialPrice : null;
                eycOrder.price= (eycOrder.couponPrice || inspPriceRule.preferentialPrice) ? (eycOrder.couponPrice ? eycOrder.couponPrice : 0) + (inspPriceRule.preferentialPrice || 0) : null;
                eycOrder.price = eycOrder.price - (eycOrder.couponPrice ? eycOrder.couponPrice : 0);
                that.setData(data);
            }
        });

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    selectVehicle(event) {
        let that = this;
        wx.navigateTo({
            url: '/pages/vehicle/vehicleFileItems',
            events: {
                // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                acceptVehicleFileFromItemsPage: function (vehicleFile) {
                    that.refreshVehicleFile(vehicleFile);
                }
            },
            success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                // res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })
            }
        })

    },
    selectInspectionStation(event) {
        let that = this;
        wx.navigateTo({
            url: `/pages/basedata/inspectionStations`,
            events: {
                acceptDataFromInspectionStationPage: function (inspectionStation) {
                    let eycOrder = that.data.eycOrder;
                    eycOrder.inspStationId = inspectionStation.inspStationId;
                    eycOrder.company = inspectionStation.company;
                    eycOrder.timeConsume = inspectionStation.timeConsume;
                    eycOrder.stationContact = inspectionStation.contact;
                    eycOrder.stationContactNum = inspectionStation.contactNum;
                    eycOrder.lng = inspectionStation.lng;
                    eycOrder.lat = inspectionStation.lat;
                    that.setData({eycOrder: eycOrder}, function () {
                        that.initAppointmentDate(eycOrder.inspStationId);
                    });

                }
            }
        });
    },
    showTimePicker(event) {
        this.setData({showTimePicker: true});
    },
    closeDatePicker(event) {
        this.setData({showTimePicker: false});
    },
    selectAppointmentTime(event) {
        this.data.eycOrder.appointmentTime = util.formatDate(new Date(event.detail));
        this.setData({eycOrder: this.data.eycOrder, showTimePicker: false});
    },
    createOrder: function (event) {
        let that = this;
        let data = that.data;
        let eycOrder = data.eycOrder;
        if (!eycOrder || !eycOrder.plateNum) {
            Toast('请选择车辆~~');
            return;
        }
        if (!eycOrder.isDoorPickUpNme) {
            Toast('请选择是否上门取车~~');
            return;
        }
        if (!eycOrder.appointmentDt) {
            Toast('请选择预约时间~~');
            return;
        }
        if (eycOrder.isDoorPickUp === 1) {
            if (!eycOrder.pickUpTime) {
                Toast('请选择取车时间段~~');
                return;
            }
            if (!eycOrder.addr) {
                Toast('请输入接车地址~~');
                return;
            }
        } else {
            if (!eycOrder.company) {
                Toast('请选择年检场地~~');
                return;
            }
        }

        if (!eycOrder.contact) {
            Toast('请输入联系人~~');
            return;
        }
        if (!eycOrder.contactNum) {
            Toast('请输入联系电话~~');
            return;
        }
        if (!data.agreeClause && !data.isEdit) {
            Toast('请查看并同意免责声明~~');
            return;
        }
        eycOrder.openid = util.getStorageSync(consts.cache_key.OPENID);
        if(eycOrder.isDoorPickUp===1){
            let eycParmPickupCar= data.eycParmPickupCar;
            if(eycParmPickupCar && eycParmPickupCar.pricePickup>0){
                eycOrder.price= eycOrder.price+eycParmPickupCar.pricePickup;
                eycOrder.costPrice= eycOrder.costPrice+eycParmPickupCar.pricePickup;
            }
        }
        util.promise(eycOrder.orderId!=null?'/editOrder':'/insertOrder', eycOrder).then(res => {
            if (res.data) {
                eycOrder = util.extend(eycOrder, res.data);
                if(!eycOrder.payStatus || eycOrder.payStatus==='UNPAID'){
                    let payParams = {
                        totalFee: eycOrder.price * 100,
                        openid: eycOrder.openid,
                        outTradeNo: eycOrder.orderNum
                    };
                    util.promise('/pay/payOrder', payParams).then(res => {
                        let data = res.data;
                        if (data) {
                            wx.requestPayment({
                                timeStamp: data.timeStamp,
                                nonceStr: data.nonceStr,
                                package: data.packageValue,
                                signType: data.signType,
                                paySign: data.paySign,
                                success(res) {
                                    eycOrder.payStatus = 'PAID';
                                    that.navigateToOrderDetail(eycOrder);
                                },
                                fail(res) {
                                    that.navigateToOrderDetail(eycOrder);
                                }
                            })
                        }

                    })
                }

            }
        })

    },
    navigateToOrderDetail(eycOrder) {
        wx.navigateTo({
            url: `/pages/order/orderDetail`,
            events: {},
            success: function (res) {
                // 通过eventChannel向被打开页面传送数据
                res.eventChannel.emit('acceptDataFromOpenerPage', eycOrder);
            }
        });
    },
    agreeClause(event) {
        this.setData({agreeClause: true});
        this.closeTerms(event);
    },
    noAgreeClause(event) {
        this.setData({agreeClause: false});
        this.closeTerms(event);
    },
    selectCoupon(event) {
        let that = this;
        let data = that.data;
        wx.navigateTo({
            url: `/pages/my/myCoupon?isSelectCoupon=true`,
            events: {
                acceptDataFromMyCouponPage: function (coupon) {
                    if (coupon) {
                        data.coupon = coupon;
                        data.eycOrder = data.eycOrder || {};
                        data.eycOrder.couponId = data.coupon.eycCouponId;
                        data.eycOrder.couponPrice = data.coupon.amount;
                        that.setData(data);
                    }
                }
            },
            success: function (res) {
                res.eventChannel.emit('acceptDataFromOpenerPage', {isSelectCoupon: true});
            }
        });
    },
    selectAppointmentDt(event) {
        let eycOrder = this.data.eycOrder;
        if (!eycOrder || (eycOrder.isDoorPickUp === 0 && !eycOrder.inspStationId)) {
            Toast('请先选择年检场地~~');
            return;
        }
        this.showTerms(event);
    },
    checkAppointedDayPickupCarNum(event){
        let that=this;
        that.setData({isCanSubmit:false});
        let eycOrder=that.data.eycOrder;
            if(eycOrder && eycOrder.isDoorPickUp===1 ){
                util.promise('/baseConfig/searchNumberOfCarPickupDaily').then(res => {
                    let eycParmPickupCar=res.data;
                    if(eycParmPickupCar) {
                        that.setData({eycParmPickupCar:eycParmPickupCar});
                        if (eycParmPickupCar.numOfCarPickupDaily > 0 && eycOrder.appointmentDt) {
                            util.promise('searchAppointedDayPickupCarNum', eycOrder.appointmentDt).then(res => {
                                if (res.data > eycParmPickupCar.numOfCarPickupDaily) {
                                    Dialog.alert({
                                        title: '信息提示',
                                        message: '亲，当日上门取车人数已约满，请选择其他日期',
                                    }).then(() => {
                                        that.setData({isCanSubmit:true});
                                    });
                                }
                            })
                        }
                    }
                });
            }
    }

});